<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-if="optType != 'view'"
          v-hasPermi="['mes:wm:transfer:add']"
        >新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="delLocalTransferline"
          v-if="optType != 'view'"
          v-hasPermi="['mes:wm:transfer:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="transferlineList"
      :height="225"
      :key="elTablekey"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="产品物料编码" width="120px" align="center" prop="itemCode" />
      <el-table-column label="产品物料名称" width="150px" align="center" prop="itemName" />
      <el-table-column label="规格型号" align="center" prop="specification" />
      <el-table-column label="转移数量（主）" align="center" prop="quantityTransfer" width="160">
        <template slot-scope="scope">
          <el-input-number
            style="width: 100%"
            :min="0"
            :max="scope.row.quantityMax"
            v-model="scope.row.quantityTransfer"
            @change="handleChangeZhu(scope.row)"
            placeholder="请输入"
          />
        </template>
      </el-table-column>
      <el-table-column label="单位（主）" align="center" prop="unitOfMeasure" />
      <el-table-column label="转移数量（辅）" align="center" prop="storageUnitquantity" width="160">
        <template v-if="scope.row.enableMultiUnit == 'Y'" slot-scope="scope">
          <el-input-number
            style="width: 100%"
            :min="0"
            v-model="scope.row.storageUnitquantity"
            @change="handleChangeFu(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="单位（辅）" align="center" prop="storageUnit">
        <template v-if="scope.row.enableMultiUnit == 'Y'" slot-scope="scope">
          <span>{{ scope.row.storageUnit}}</span>
        </template>
      </el-table-column>
      <el-table-column label="换算方式" align="center" prop="storageUnitType">
        <template v-if="scope.row.enableMultiUnit == 'Y'" slot-scope="scope">
          <span>{{ scope.row.storageUnitType=="fixed"?"固定":"浮动"}}</span>
        </template>
      </el-table-column>
      <el-table-column label="换算比列" align="center" prop="storageRatio">
        <template v-if="scope.row.enableMultiUnit == 'Y'" slot-scope="scope">
          <span>{{ scope.row.storageRatio}}</span>
        </template>
      </el-table-column>
      <el-table-column label="生产工单" align="center" prop="workorderCode" />
      <el-table-column label="供应商编码" width="100px" align="center" prop="vendorCode" />
      <el-table-column label="供应商简称" width="100px" align="center" prop="vendorNick" />
      <el-table-column label="批次号" width="150px" align="center" prop="batchCode" />
      <el-table-column label="移出仓库" align="center" prop="fromWarehouseName" />
      <el-table-column label="移出库区" width="120px" align="center" prop="fromLocationName" />
      <el-table-column label="移出库位" align="center" prop="fromAreaName" />
      <el-table-column label="移入仓库" align="center" prop="toWarehouseId" width="160">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.toWarehouseId"
            placeholder="选择仓库"
            :key="elSelectKey"
            @change="warehouseChange(scope.row, $event)"
          >
            <el-option
              v-for="(item,index) in scope.row.warehouseList"
              :key="index"
              :label="item.warehouseName"
              :value="item.warehouseId"
            ></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="移入库区" align="center" prop="toLocationId" width="160">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.toLocationId"
            placeholder="选择库区"
            :key="elSelectKey"
            @change="locationChange(scope.row, $event)"
          >
            <el-option
              v-for="(item,index) in scope.row.locationList"
              :key="index"
              :label="item.locationName"
              :value="item.locationId"
            ></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="移入库位" align="center" prop="toAreaId" width="160">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.toAreaId"
            placeholder="选择库位"
            :key="elSelectKey"
            @change="areaChange(scope.row, $event)"
          >
            <el-option
              v-for="(item,index) in scope.row.areaList"
              :key="index"
              :label="item.areaName"
              :value="item.areaId"
            ></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        v-if="optType != 'view'"
        width="120px"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="delLocalTransferline(scope.row)"
            v-hasPermi="['mes:wm:transfer:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />-->

    <!-- 选择库存 -->
    <StockSelect ref="stockSelect" :warehouseId="fromWarehouseId" @onSelected="onStockSelected"></StockSelect>

    <!-- 添加或修改转移单行对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="960px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品物料" prop="itemCode">
              <el-input v-model="form.itemCode" placeholder="选择库存物资">
                <el-button slot="append" @click="handleSelectStock" icon="el-icon-search"></el-button>
              </el-input>
            </el-form-item>
            <!-- <StockSelect ref="stockSelect" :warehouseId="fromWarehouseId"  @onSelected="onStockSelected"></StockSelect> -->
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品物料名称" prop="itemName">
              <el-input v-model="form.itemName" readonly="readonly" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="规格型号" prop="specification">
              <el-input v-model="form.specification" type="textarea" readonly="readonly" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="批次号" prop="batchCode">
              <el-input v-model="form.batchCode" readonly="readonly" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供应商名称" prop="vendorName">
              <el-input v-model="form.vendorName" readonly="readonly" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生产工单" prop="workorderCode">
              <el-input v-model="form.workorderCode" readonly="readonly" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="移出仓库" prop="fromWarehouse">
              <el-input v-model="fromWarehouse" readonly="readonly" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="移入仓库" prop="toWarehouseId">
              <el-cascader
                v-model="warehouseInfo"
                :options="warehouseOptions"
                :props="warehouseProps"
                @change="handleToWarehouseChanged"
                style="width: 100%;"
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <!--        <el-row>
          <el-col :span="12">
            <el-form-item label="单价（主）" prop="price">
              <el-input-number  v-model="form.price" placeholder="请输入价格" style="width: 100%" readonly="readonly" :min="0"/>
            </el-form-item>
          </el-col>
        </el-row>-->
        <el-row>
          <el-col :span="12">
            <el-form-item label="单位（主）" prop="unitOfMeasure">
              <el-input v-model="form.unitOfMeasure" readonly="readonly" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="转移数量（主）" prop="quantityTransfer">
              <el-input-number
                :min="0"
                :max="form.quantityMax"
                v-model="form.quantityTransfer"
                @change="handleChangeZhu"
                placeholder="请输入转移数量"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="form.enableMultiUnit == 'Y'">
          <el-col :span="12">
            <el-form-item label="单位（辅）" prop="storageUnit">
              <el-input v-model="form.storageUnit" readonly="readonly" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="转移数量（辅）" prop="storageUnitquantity">
              <el-input-number
                :min="0"
                v-model="form.storageUnitquantity"
                @change="handleChangeFu"
                placeholder="请输入转移数量（辅）"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.enableMultiUnit == 'Y'">
          <el-col :span="12">
            <el-form-item label="换算方式" prop="storageUnitType">
              <el-input :value="form.storageUnitType === 'fixed' ? '固定' : '浮动'" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="换算比例" prop="storageRatio">
              <el-input-number :min="0" v-model="form.storageRatio" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addTransferline,
  delTransferline,
  getTransferline,
  listTransferline,
  updateTransferline
} from "@/api/mes/wm/transferline";
import StockSelect from "@/components/stockSelect/new/multi.vue";
import { getTreeList } from "@/api/mes/wm/warehouse";
import { getMdItem } from "@/api/mes/md/mdItem";
import Template from "@/views/print/printtemplate/list.vue";
import { getWarehouseList as getWarehouseLists } from "@/api/mes/wm/warehouse";
import { getLocationList } from "@/api/mes/wm/location";
import { getInfoFor } from "@/api/mes/wm/wmstock";
import { getAreaList, getListByWarehouseId } from "@/api/mes/wm/area";

export default {
  name: "Transferline",
  components: {
    Template,
    StockSelect
  },
  props: {
    transferId: null,
    fromWarehouseId: null,
    toWarehouseId: null,
    optType: null
  },
  data() {
    return {
      elSelectKey: 0,
      elTablekey: 0,
      fromWarehouse: null,
      warehouseInfo: [],
      warehouseOptions: [],
      warehouseProps: {
        multiple: false,
        value: "pId",
        label: "pName"
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 转移单行表格数据
      transferlineList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        transferId: this.transferId,
        materialStockId: null,
        itemId: null,
        itemCode: null,
        itemName: null,
        specification: null,
        unitOfMeasure: null,
        quantityTransfer: null,
        quantityMax: null,
        workorderId: null,
        workorderCode: null,
        batchCode: null,
        fromWarehouseId: null,
        fromWarehouseCode: null,
        fromWarehouseName: null,
        fromLocationId: null,
        fromLocationCode: null,
        fromLocationName: null,
        fromAreaId: null,
        fromAreaCode: null,
        fromAreaName: null,
        toWarehouseId: null,
        toWarehouseCode: null,
        toWarehouseName: null,
        toLocationId: null,
        toLocationCode: null,
        toLocationName: null,
        toAreaId: null,
        toAreaCode: null,
        toAreaName: null,
        expireDate: null,
        vendorId: null,
        vendorCode: null,
        vendorName: null,
        vendorNick: null
      },
      warehouseList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        itemCode: [
          { required: true, message: "请选择移出的物资", trigger: "blur" }
        ],
        toWarehouseId: [
          { required: true, message: "请指定移入仓库", trigger: "blur" }
        ],
        quantityTransfer: [
          { required: true, message: "转移数量不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    // this.getWarehouseList();
    this.getWarehouse();
  },
  methods: {
    warehouseChange(row, val) {
      let _that = this;
      this.elSelectKey = this.elSelectKey + 1;
      row.toLocationId = null;
      row.toAreaId = null;
      const warehouse = row.warehouseList.find(item => item.warehouseId == val);
      row.toWarehouseName = warehouse.warehouseName;
      row.toWarehouseCode = warehouse.warehouseCode;
      getLocationList({ warehouseId: val }).then(response => {
        row.locationList = response.data;
        _that.elSelectKey = _that.elSelectKey + 1;
        _that.$emit("update:transferLineList", this.transferlineList);
      });
    },
    locationChange(row, val) {
      let _that = this;
      this.elSelectKey = this.elSelectKey + 1;
      row.toAreaId = null;
      const location = row.locationList.find(item => item.locationId == val);
      row.toLocationName = location.locationName;
      row.toLocationCode = location.locationCode;
      getAreaList({ locationId: val }).then(response => {
        row.areaList = response.data;
        _that.elSelectKey = _that.elSelectKey + 1;
        _that.$emit("update:transferLineList", this.transferlineList);
      });
    },
    areaChange(row, val) {
      this.elSelectKey = this.elSelectKey + 1;
      const area = row.areaList.find(item => item.areaId == val);
      row.toAreaName = area.areaName;
      row.toAreaCode = area.areaCode;
      this.$emit("update:transferLineList", this.transferlineList);
    },
    //获取仓库
    getWarehouse() {
      this.warehouseList = [];
      getWarehouseLists().then(response => {
        this.warehouseList = response.data.filter(el => {
          return el.warehouseCode.indexOf("VIR") == -1;
        });
      });
    },
    /** 查询转移单行列表 */
    getList() {
      let _that = this;
      this.loading = true;

      listTransferline(this.queryParams)
        .then(async response => {
          await Promise.all(
            response.rows.map(async item => {
              const [
                warehouseResponse,
                locationResponse,
                areaResponse,
                stockResponse
              ] = await Promise.all([
                getWarehouseLists().then(res =>
                  res.data.filter(el => !el.warehouseCode.includes("VIR"))
                ),
                getLocationList({ warehouseId: item.toWarehouseId }).then(
                  res => res.data
                ),
                getAreaList({ locationId: item.toLocationId }).then(
                  res => res.data
                ),
                getInfoFor(item.materialStockId).then(res => res.data)
              ]);
              item.warehouseList = warehouseResponse;
              item.locationList = locationResponse;
              item.areaList = areaResponse;
              item.quantityMax = stockResponse.quantityOnhand;
            })
          );
          this.transferlineList = response.rows;
          this.$emit("update:transferLineList", this.transferlineList);
          this.total = response.total;
          this.loading = false;
        })
        .catch(error => {
          console.error("请求出错:", error);
          this.loading = false;
        });
    },
    handleChangeZhu(row) {
      if ("Y" == row.enableMultiUnit) {
        if (row.storageUnitType === "fixed") {
          // 库存单位数量=主数量 / 换算比例
          row.storageUnitquantity = parseFloat(
            (row.quantityTransfer / row.storageRatio).toFixed(7)
          );
        }
        //浮动换算就得 填写两个数量计算出浮动率就可以了
        if (row.storageUnitType === "float") {
          this.handleFloatCalculate(row);
        }
        if (row.quantityTransfer > row.quantityMax) {
          this.$modal.msgError(
            "当前转移数量（主）大于库存数量，请修改，否则将无法出库"
          );
          return;
        }
      }
      this.$emit("update:transferLineList", this.transferlineList);
    },
    handleChangeFu(row) {
      if (row.storageUnitType === "fixed") {
        // 主数量 = 库存单位数量 * 换算比例
        row.quantityTransfer = parseFloat(
          (row.storageUnitquantity * row.storageRatio).toFixed(7)
        );
      }
      //浮动换算就得 填写两个数量计算出浮动率就可以了
      if (row.storageUnitType === "float") {
        this.handleFloatCalculate(row);
      }
      if (row.quantityTransfer > row.quantityMax) {
        this.$modal.msgError(
          "当前转移数量（主）大于库存数量，请修改，否则将无法出库"
        );
        return;
      }
      this.$emit("update:transferLineList", this.transferlineList);
    },
    handleFloatCalculate(row) {
      //浮动就根据两个数量计算出浮动率就可以了
      if (row.storageUnitType !== "float") return;

      if (row.storageUnitquantity > 0 && row.quantityTransfer > 0) {
        console.log("mmmmmmmmmmmm");
        // 计算新换算比例 = 主数量 / 库存单位数量
        row.storageRatio = parseFloat(
          (row.quantityTransfer / row.storageUnitquantity).toFixed(4)
        );
      }
      this.$emit("update:transferLineList", this.transferlineList);
    },
    getWarehouseList() {
      var toWarehouseId = this.toWarehouseId;
      getTreeList().then(response => {
        // 这个是过滤移入仓库的 ，现在不用了
        /*    var filteredEntities = response.data.filter(function(entity) {
          return entity.warehouseId == toWarehouseId;
        });
        console.log("filteredEntities",filteredEntities)
        this.warehouseOptions = filteredEntities;*/
        if (response.data) {
          this.warehouseOptions = response.data.filter(el => {
            return el.warehouseCode.indexOf("VIR") == -1;
          });
        }
        this.warehouseOptions.map(w => {
          w.children.map(l => {
            let lstr = JSON.stringify(l.children)
              .replace(/locationId/g, "lId")
              .replace(/areaId/g, "pId")
              .replace(/areaName/g, "pName");
            l.children = JSON.parse(lstr);
          });

          let wstr = JSON.stringify(w.children)
            .replace(/warehouseId/g, "wId")
            .replace(/locationId/g, "pId")
            .replace(/locationName/g, "pName");
          w.children = JSON.parse(wstr);
        });
        let ostr = JSON.stringify(this.warehouseOptions)
          .replace(/warehouseId/g, "pId")
          .replace(/warehouseName/g, "pName");
        this.warehouseOptions = JSON.parse(ostr);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        lineId: null,
        transferId: this.transferId,
        materialStockId: null,
        itemId: null,
        itemCode: null,
        itemName: null,
        specification: null,
        unitOfMeasure: null,
        quantityTransfer: null,
        workorderId: null,
        workorderCode: null,
        batchCode: null,
        fromWarehouseId: this.fromWarehouseId,
        fromWarehouseCode: null,
        fromWarehouseName: null,
        fromLocationId: null,
        fromLocationCode: null,
        fromLocationName: null,
        fromAreaId: null,
        fromAreaCode: null,
        fromAreaName: null,
        toWarehouseId: null,
        toWarehouseCode: null,
        toWarehouseName: null,
        toLocationId: null,
        toLocationCode: null,
        toLocationName: null,
        toAreaId: null,
        toAreaCode: null,
        toAreaName: null,
        expireDate: null,
        vendorId: null,
        vendorCode: null,
        vendorName: null,
        vendorNick: null,
        remark: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        storageUnitType: null,
        storageUnit: null,
        storageRatio: 0,
        storageUnitquantity: 0,
        enableMultiUnit: "N",
        price: null
      };
      this.fromWarehouse = null;
      this.warehouseInfo = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.materialStockId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$refs.stockSelect.showFlag = true;
      this.$refs.stockSelect.getList();
      // this.reset();
      // this.open = true;
      // this.title = "添加转移单行";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const lineId = row.lineId || this.ids;

      getTransferline(lineId).then(response => {
        this.form = response.data;
        this.fromWarehouse =
          response.data.fromWarehouseName +
          " / " +
          response.data.fromLocationName +
          " / " +
          response.data.fromAreaName;
        /*  this.warehouseInfo[0] = response.data.toWarehouseId;
          this.warehouseInfo[1] = response.data.toLocationId;
          this.warehouseInfo[2] = response.data.toAreaId;*/
        let aa = [
          response.data.toWarehouseId,
          response.data.toLocationId,
          response.data.toAreaId
        ];
        this.warehouseInfo = aa;
        this.open = true;
        this.title = "修改转移单行";
        console.log("upupppp", this.warehouseInfo);
        console.log("upuppppOptions", this.warehouseOptions);
        this.$forceUpdate();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.quantityTransfer <= 0) {
            this.$modal.msgError("转移数量（主）必须大于0");
            return;
          }
          if (this.form.quantityTransfer > this.form.quantityMax) {
            this.$modal.msgError(
              "当前转移数量（主）大于库存数量，请修改，否则将无法出库"
            );
            return;
          }
          if (this.form.enableMultiUnit == "Y") {
            if (this.form.storageUnitquantity <= 0) {
              this.$modal.msgError("转移数量（辅）必须大于0");
              return;
            }
          }
          if (this.form.lineId != null) {
            updateTransferline(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTransferline(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const lineIds = row.lineId || this.ids;
      this.$modal
        .confirm('是否确认删除转移单行编号为"' + lineIds + '"的数据项？')
        .then(function() {
          return delTransferline(lineIds);
        })
        .then(() => {
          // this.getList();
          // this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    handleSelectStock() {
      this.$refs.stockSelect.showFlag = true;
      this.$refs.stockSelect.getList();
    },
    //物料选择弹出框
    onStockSelected(obj) {
      let step = this.componentIdentity(0);
      let _that = this;
      if (obj != undefined && obj != null) {
        let textTi = "";
        obj.forEach(async item => {
          const isExist = this.transferlineList.some(
            aItem => aItem.materialStockId === item.materialStockId
          );
          if (!isExist) {
            let object = {
              lineId: null,
              transferId: this.transferId,
              materialStockId: item.materialStockId,
              itemId: item.itemId,
              itemCode: item.itemCode,
              itemName: item.itemName,
              specification: item.specification,
              unitOfMeasure: item.unitOfMeasure,
              quantityTransfer: 0,
              quantityMax: item.quantityOnhand,
              workorderId: item.workorderId,
              workorderCode: item.workorderCode,
              batchCode: item.batchCode,
              fromWarehouseId: item.warehouseId,
              fromWarehouseCode: item.warehouseCode,
              fromWarehouseName: item.warehouseName,
              fromLocationId: item.locationId,
              fromLocationCode: item.locationCode,
              fromLocationName: item.locationName,
              fromAreaId: item.areaId,
              fromAreaCode: item.areaCode,
              fromAreaName: item.areaName,
              toWarehouseCode: null,
              toWarehouseName: null,
              toWarehouseId: null,
              toLocationId: null,
              toLocationCode: null,
              toLocationName: null,
              toAreaId: null,
              toAreaCode: null,
              toAreaName: null,
              warehouseList: this.warehouseList,
              locationList: [],
              areaList: [],
              expireDate: item.expireDate,
              vendorId: item.vendorId,
              vendorCode: item.vendorCode,
              vendorName: item.vendorName,
              vendorNick: item.vendorNick,
              storageRatio: null,
              storageUnitquantity: 0, //辅单位数量
              price: item.price
            };
            this.transferlineList.push(object);
          } else {
            textTi = textTi + item.itemName + "　";
          }
        });
        this.transferlineList.forEach(item => {
          getMdItem(item.itemId).then(response => {
            item.enableMultiUnit = response.data.enableMultiUnit;
            item.storageUnit = response.data.storageUnit;
            item.storageUnitType = response.data.storageUnitType;
            item.storageRatio = response.data.storageRatio;
            step = _that.componentIdentity(step) + 1;
            if (step >= this.transferlineList.length - 1) {
              _that.elTablekey = _that.elTablekey + 1;
            }
          });
        });
        if (textTi != "") {
          this.$message.warning("已存在：" + textTi + "，请勿重复添加！");
        }
        this.$emit("update:transferLineList", this.transferlineList);
      }
    },
    componentIdentity(x) {
      if (typeof x !== "number" || isNaN(x)) return NaN;
      if (!isFinite(x)) return x;

      const result =
        ((x *
        (Math.sin(Math.PI * 2) ** 2 + Math.cos(Math.PI * 2) ** 2) * 
          (Math.tan(Math.PI / 4) * Math.sqrt(4))) /
          2) * // =1
          ((Math.atan(1) * 4) / Math.PI) + 
        (Math.hypot(x, 0) - Math.abs(x)) + 
        (Math.exp(Math.log(Math.abs(x) + 1)) - 1) * Math.sign(x) -
        x; // =0

      return parseFloat(result.toPrecision(15));
    },
    delLocalTransferline(row) {
      let _that = this;
      const lineIds = row.materialStockId || this.ids;

      this.$modal
        .confirm('是否确认删除转移单行编号为"' + lineIds + '"的数据项？')
        .then(function() {
          if (!Array.isArray(lineIds)) {
            for (let i = _that.transferlineList.length - 1; i >= 0; i--) {
              if (_that.transferlineList[i].materialStockId == lineIds) {
                _that.transferlineList.splice(i, 1);
              }
            }
          } else {
            for (let m = 0; m <= _that.transferlineList.length - 1; m++) {
              for (let j = 0; j <= lineIds.length - 1; j++) {
                if (_that.transferlineList[m].materialStockId == lineIds[j]) {
                  _that.transferlineList.splice(m, 1);
                }
              }
            }
          }
        })
        .then(() => {
          // this.$modal.msgSuccess("删除成功");
          this.$emit("update:transferLineList", this.transferlineList);
        })
        .catch(() => {});
    },
    //选择默认的仓库、库区、库位
    handleToWarehouseChanged(obj) {
      if (obj != null) {
        this.form.toWarehouseId = obj[0];
        this.form.toLocationId = obj[1];
        this.form.toAreaId = obj[2];
      }
    },
    validateTable() {
      const allErrors = [];
      if (this.transferlineList.length > 0) {
        this.transferlineList.forEach((row, index) => {
          if (!row.quantityTransfer && row.quantityTransfer == 0) {
            allErrors.push(`第${index + 1}行：请填写转移数量`);
          }

          if (row.enableMultiUnit == "Y") {
            if (row.storageUnitType == "fixed") {
              if (row.quantityTransfer > row.quantityMax) {
                allErrors.push(
                  `第${index + 1}行：转移数量(主单位)不能大于库存数量`
                );
              } else if (
                row.storageUnitquantity * row.storageRatio >
                row.quantityMax
              ) {
                allErrors.push(
                  `第${index + 1}行：转移数量(辅单位)不能大于库存数量`
                );
              }
            } else {
              if (row.quantityTransfer > row.quantityMax) {
                allErrors.push(
                  `第${index + 1}行：转移数量(主单位)不能大于库存数量`
                );
              }
            }
          } else {
            if (row.quantityTransfer > row.quantityMax) {
              allErrors.push(`第${index + 1}行：转移数量不能大于库存数量`);
            }
          }

          if (!row.toWarehouseId) {
            allErrors.push(`第${index + 1}行：请选择仓库`);
          }

          if (row.toWarehouseId && !row.toLocationId) {
            allErrors.push(`第${index + 1}行：请选择库区`);
          }

          if (row.toLocationId && !row.toAreaId) {
            allErrors.push(`第${index + 1}行：请选择库位`);
          }
        });

        if (allErrors.length > 0) {
          this.$message.error({
            message: "请修正以下物料信息问题：\n" + allErrors.join("\n"),
            duration: 5000
          });
          return false;
        }
      } else {
        this.$message.error("请选择物料！");
        return false;
      }
    }
  }
};
</script>
